<?php
// 引入函数库
include_once('functions.php');

// 验证码宽高
$width = 80;
$height = 34;

// 创建一个画布
$result = imagecreatetruecolor($width,$height);

// 定义一个背景色
$bgColor = imagecolorallocate($result,238,238,238);

// 把背景色加入画布里
imagefilledrectangle($result,0,0,$width,$height,$bgColor);

// 定义一个文字颜色
$textColor = imagecolorallocate($result,255,0,0);

// 随机分别生成四个字符
$code_1 = build_randstr(1);
$code_2 = build_randstr(1);
$code_3 = build_randstr(1);
$code_4 = build_randstr(1);

// 获取项目根目录
$path = $_SERVER['DOCUMENT_ROOT'];

// 定义字体路径
$fontPath = $path . '/assets/fonts/OpenSans-Light.ttf';

// 把字符加入画布里
imagettftext($result,16,mt_rand(-30,30),8,26,$textColor,$fontPath,$code_1);
imagettftext($result,16,mt_rand(-30,30),23,26,$textColor,$fontPath,$code_2);
imagettftext($result,16,mt_rand(-30,30),40,26,$textColor,$fontPath,$code_3);
imagettftext($result,16,mt_rand(-30,30),60,26,$textColor,$fontPath,$code_4);

// 绘制一些点状像素
for($i = 0;$i <= 10;$i++){
    imagesetpixel($result,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($result,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}

// 绘制一些线像素
for($i = 0;$i <= 5;$i++){
    imageline($result,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($result,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}

// 开启session
session_start();

// 设置会话变量
$_SESSION['code'] = $code_1 . $code_2 . $code_3 . $code_4;

// 设置头信息，告诉浏览器，这是图片，不是文档
header('Content-Type:image/png');

// 输出图片
imagepng($result);
